/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: CountChildHandler
 * Author:   zengjian
 * Date:     2018/9/20 21:02
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package org.yinxue.swing.im.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.yinxue.swing.im.domain.event.ClientListGetEvent;
import org.yinxue.swing.im.domain.event.EventPublisher;
import org.yinxue.swing.im.domain.event.MessageReceiveEvent;

import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * 〈〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/9/20 21:02
 */
public class ClientHandler extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
        ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
        ch.pipeline().addLast(new SimpleChannelInboundHandler() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                String receiveMsg = (String) msg;
                System.out.println("IMClient接收到响应:\n" + msg);
                if (receiveMsg.startsWith("GET")) {
                    String[] ips = receiveMsg.split(";")[1].split(",");
                    System.out.println(Arrays.toString(ips));
                    EventPublisher.instance().publish(new ClientListGetEvent(new Object(), ips));
                    return;
                }
//                if (receiveMsg.startsWith("MSG")){
                EventPublisher.instance().publish(new MessageReceiveEvent(receiveMsg));
//                }
            }
        });
    }
}